package cn.krui.helper.filter;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Arrays;

import com.fasterxml.jackson.core.JsonProcessingException;

import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author zc
 */
@ControllerAdvice
public class JsonReturnHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(org.springframework.core.MethodParameter returnType,
            Class<? extends HttpMessageConverter<?>> converterType) {
        boolean hasJsonAnno = returnType.getMethodAnnotation(JSON.class) != null;
        return hasJsonAnno;
    }

    @Override
    public Object beforeBodyWrite(Object body, org.springframework.core.MethodParameter returnType,
            MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request, ServerHttpResponse response) {
        // 设置这个就是最终的处理类了，处理完不再去找下一个类进行处理
        // 获得注解并执行filter方法 最后返回
        Annotation[] annos = returnType.getMethodAnnotations();
        JsonSerializer jsonSerializer = new JsonSerializer();
        Arrays.asList(annos).forEach(a -> {
            if (a instanceof JSON) {
                JSON json = (JSON) a;
                jsonSerializer.filter(json.type(), json.include(), json.filter());
            }
        });
        String json = null;
        try {
            json = jsonSerializer.toJson(body);
            response.getHeaders().set("Content-Type", "application/json; charset=utf-8");
            response.getBody().write(json.getBytes());
            return null;
        } catch (JsonProcessingException e) {
            System.out.println("JSON转换输出错误，你解决不了，赶紧跑……"+e.getMessage());
            // e.printStackTrace();
        } catch (IOException e) {
            System.out.println("JSON转换输出错误，你解决不了，赶紧跑……"+e.getMessage());
            // e.printStackTrace();
        }

    return body;
  }
}